import { logDataCache, dumpPathCache, componentCache } from '../utils/cacheManager'
import { useFileDataStore } from '../stores/fileData'

// 内存使用阈值配置
export interface MemoryThresholds {
  warning: number    // 警告阈值 (MB)
  critical: number   // 严重阈值 (MB)
  maximum: number    // 最大阈值 (MB)
}

// 内存统计信息
export interface MemoryStats {
  totalUsed: number
  cacheUsed: number
  fileDataUsed: number
  availableMemory: number
  usagePercentage: number
  timestamp: number
}

// 清理策略
export enum CleanupStrategy {
  LRU = 'lru',                    // 最近最少使用
  SIZE_BASED = 'size_based',      // 基于大小
  TIME_BASED = 'time_based',      // 基于时间
  PRIORITY_BASED = 'priority_based' // 基于优先级
}

// 清理结果
export interface CleanupResult {
  freedMemory: number
  itemsRemoved: number
  strategy: CleanupStrategy
  duration: number
  success: boolean
}

/**
 * 智能内存管理服务
 * 负责监控内存使用、自动清理缓存、优化内存分配
 */
export class MemoryManagementService {
  private thresholds: MemoryThresholds = {
    warning: 512,   // 512MB
    critical: 1024, // 1GB
    maximum: 2048   // 2GB
  }
  
  private monitoringInterval?: NodeJS.Timeout
  private isMonitoring = false
  private memoryHistory: MemoryStats[] = []
  private maxHistorySize = 100
  private _fileDataStore: any = null
  private cleanupInProgress = false

  private get fileDataStore() {
    if (!this._fileDataStore) {
      this._fileDataStore = useFileDataStore()
    }
    return this._fileDataStore
  }
  private lastCleanupTime = 0
  private minCleanupInterval = 30000 // 30秒最小清理间隔

  constructor(customThresholds?: Partial<MemoryThresholds>) {
    if (customThresholds) {
      this.thresholds = { ...this.thresholds, ...customThresholds }
    }
    this.startMonitoring()
  }

  /**
   * 开始内存监控
   */
  startMonitoring(interval: number = 10000): void {
    if (this.isMonitoring) return
    
    this.isMonitoring = true
    console.log('[MemoryManagement] 开始内存监控')
    
    this.monitoringInterval = setInterval(async () => {
      await this.checkMemoryUsage()
    }, interval)
    
    // 立即执行一次检查
    this.checkMemoryUsage()
  }

  /**
   * 停止内存监控
   */
  stopMonitoring(): void {
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval)
      this.monitoringInterval = undefined
    }
    this.isMonitoring = false
    console.log('[MemoryManagement] 停止内存监控')
  }

  /**
   * 检查内存使用情况
   */
  async checkMemoryUsage(): Promise<MemoryStats> {
    const stats = await this.getMemoryStats()
    
    // 记录历史数据
    this.addToHistory(stats)
    
    // 检查是否需要清理
    if (stats.totalUsed > this.thresholds.critical) {
      console.warn(`[MemoryManagement] 内存使用达到严重阈值: ${stats.totalUsed}MB`)
      await this.performEmergencyCleanup()
    } else if (stats.totalUsed > this.thresholds.warning) {
      console.warn(`[MemoryManagement] 内存使用达到警告阈值: ${stats.totalUsed}MB`)
      await this.performSmartCleanup()
    }
    
    return stats
  }

  /**
   * 获取内存统计信息
   */
  async getMemoryStats(): Promise<MemoryStats> {
    try {
      // 获取缓存使用情况
      const logCacheStats = logDataCache.getStats()
      const dumpCacheStats = dumpPathCache.getStats()
      const componentCacheStats = componentCache.getStats()
      
      const cacheUsed = parseFloat(logCacheStats.memoryUsage) + parseFloat(dumpCacheStats.memoryUsage) + parseFloat(componentCacheStats.memoryUsage)
      
      // 获取文件数据使用情况
      const fileDataUsage = this.fileDataStore.getMemoryUsage()
      const fileDataUsed = fileDataUsage.totalSize / (1024 * 1024) // 转换为MB
      
      const totalUsed = cacheUsed + fileDataUsed
      
      // 估算可用内存（基于浏览器限制）
      const estimatedAvailable = this.estimateAvailableMemory()
      const usagePercentage = (totalUsed / (totalUsed + estimatedAvailable)) * 100
      
      return {
        totalUsed,
        cacheUsed,
        fileDataUsed,
        availableMemory: estimatedAvailable,
        usagePercentage,
        timestamp: Date.now()
      }
    } catch (error) {
      console.error('[MemoryManagement] 获取内存统计失败:', error)
      return {
        totalUsed: 0,
        cacheUsed: 0,
        fileDataUsed: 0,
        availableMemory: 0,
        usagePercentage: 0,
        timestamp: Date.now()
      }
    }
  }

  /**
   * 执行智能清理
   */
  async performSmartCleanup(): Promise<CleanupResult> {
    if (this.cleanupInProgress) {
      console.log('[MemoryManagement] 清理正在进行中，跳过')
      return this.createEmptyCleanupResult()
    }
    
    if (Date.now() - this.lastCleanupTime < this.minCleanupInterval) {
      console.log('[MemoryManagement] 清理间隔太短，跳过')
      return this.createEmptyCleanupResult()
    }
    
    this.cleanupInProgress = true
    const startTime = performance.now()
    
    try {
      console.log('[MemoryManagement] 开始智能清理')
      
      let totalFreed = 0
      let totalRemoved = 0
      
      // 策略1: 清理过期缓存
      const expiredResult = await this.cleanupExpiredCache()
      totalFreed += expiredResult.freedMemory
      totalRemoved += expiredResult.itemsRemoved
      
      // 策略2: LRU清理
      if (totalFreed < 50) { // 如果释放的内存少于50MB，继续清理
        const lruResult = await this.cleanupLRU(100) // 清理100个最少使用的项目
        totalFreed += lruResult.freedMemory
        totalRemoved += lruResult.itemsRemoved
      }
      
      // 策略3: 清理大文件
      if (totalFreed < 100) { // 如果释放的内存少于100MB，清理大文件
        const largeFileResult = await this.cleanupLargeFiles()
        totalFreed += largeFileResult.freedMemory
        totalRemoved += largeFileResult.itemsRemoved
      }
      
      const duration = performance.now() - startTime
      this.lastCleanupTime = Date.now()
      
      console.log(`[MemoryManagement] 智能清理完成，释放内存: ${totalFreed.toFixed(2)}MB，移除项目: ${totalRemoved}个，耗时: ${duration.toFixed(2)}ms`)
      
      return {
        freedMemory: totalFreed,
        itemsRemoved: totalRemoved,
        strategy: CleanupStrategy.LRU,
        duration,
        success: true
      }
    } catch (error) {
      console.error('[MemoryManagement] 智能清理失败:', error)
      return {
        freedMemory: 0,
        itemsRemoved: 0,
        strategy: CleanupStrategy.LRU,
        duration: performance.now() - startTime,
        success: false
      }
    } finally {
      this.cleanupInProgress = false
    }
  }

  /**
   * 执行紧急清理
   */
  async performEmergencyCleanup(): Promise<CleanupResult> {
    console.warn('[MemoryManagement] 执行紧急清理')
    
    const startTime = performance.now()
    let totalFreed = 0
    let totalRemoved = 0
    
    try {
      // 清理所有非关键缓存
      const cacheResult = await this.clearNonCriticalCache()
      totalFreed += cacheResult.freedMemory
      totalRemoved += cacheResult.itemsRemoved
      
      // 清理大型文件数据
      const fileResult = await this.clearLargeFileData()
      totalFreed += fileResult.freedMemory
      totalRemoved += fileResult.itemsRemoved
      
      // 强制垃圾回收（如果可用）
      this.forceGarbageCollection()
      
      const duration = performance.now() - startTime
      
      console.warn(`[MemoryManagement] 紧急清理完成，释放内存: ${totalFreed.toFixed(2)}MB，移除项目: ${totalRemoved}个`)
      
      return {
        freedMemory: totalFreed,
        itemsRemoved: totalRemoved,
        strategy: CleanupStrategy.PRIORITY_BASED,
        duration,
        success: true
      }
    } catch (error) {
      console.error('[MemoryManagement] 紧急清理失败:', error)
      return {
        freedMemory: 0,
        itemsRemoved: 0,
        strategy: CleanupStrategy.PRIORITY_BASED,
        duration: performance.now() - startTime,
        success: false
      }
    }
  }

  /**
   * 清理过期缓存
   */
  private async cleanupExpiredCache(): Promise<CleanupResult> {
    const startTime = performance.now()
    let freedMemory = 0
    let itemsRemoved = 0
    
    // 这里需要实现缓存管理器的过期清理功能
    // 由于当前缓存管理器没有直接的过期清理方法，我们模拟实现
    
    const duration = performance.now() - startTime
    
    return {
      freedMemory,
      itemsRemoved,
      strategy: CleanupStrategy.TIME_BASED,
      duration,
      success: true
    }
  }

  /**
   * LRU清理
   */
  private async cleanupLRU(_maxItems: number): Promise<CleanupResult> {
    const startTime = performance.now()
    let freedMemory = 0
    let itemsRemoved = 0
    
    // 这里需要实现LRU清理逻辑
    // 由于当前缓存管理器已经有LRU功能，我们可以触发清理
    
    const duration = performance.now() - startTime
    
    return {
      freedMemory,
      itemsRemoved,
      strategy: CleanupStrategy.LRU,
      duration,
      success: true
    }
  }

  /**
   * 清理大文件
   */
  private async cleanupLargeFiles(): Promise<CleanupResult> {
    const startTime = performance.now()
    let freedMemory = 0
    let itemsRemoved = 0
    
    try {
      const fileDataUsage = this.fileDataStore.getMemoryUsage()
      
      // 找出大于10MB的文件并清理一些
      // const largeFileThreshold = 10 * 1024 * 1024 // 10MB
      
      // 这里需要实现具体的大文件清理逻辑
      // 由于fileDataStore没有提供按大小清理的方法，我们记录需要改进的地方
      
      console.log(`[MemoryManagement] 检测到 ${fileDataUsage.fileCount} 个文件，总大小: ${(fileDataUsage.totalSize / 1024 / 1024).toFixed(2)}MB`)
      
    } catch (error) {
      console.error('[MemoryManagement] 清理大文件失败:', error)
    }
    
    const duration = performance.now() - startTime
    
    return {
      freedMemory,
      itemsRemoved,
      strategy: CleanupStrategy.SIZE_BASED,
      duration,
      success: true
    }
  }

  /**
   * 清理非关键缓存
   */
  private async clearNonCriticalCache(): Promise<CleanupResult> {
    const startTime = performance.now()
    let freedMemory = 0
    let itemsRemoved = 0
    
    try {
      // 清理组件缓存（非关键）
      const componentStats = componentCache.getStats()
      freedMemory += parseFloat(componentStats.memoryUsage.replace('MB', '')) || 0
      itemsRemoved += componentStats.entryCount
      componentCache.clear()
      
      // 清理转储路径缓存（非关键）
      const dumpStats = dumpPathCache.getStats()
      freedMemory += parseFloat(dumpStats.memoryUsage.replace('MB', '')) || 0
      itemsRemoved += dumpStats.entryCount
      dumpPathCache.clear()
      
      console.log(`[MemoryManagement] 清理非关键缓存完成`)
    } catch (error) {
      console.error('[MemoryManagement] 清理非关键缓存失败:', error)
    }
    
    const duration = performance.now() - startTime
    
    return {
      freedMemory,
      itemsRemoved,
      strategy: CleanupStrategy.PRIORITY_BASED,
      duration,
      success: true
    }
  }

  /**
   * 清理大型文件数据
   */
  private async clearLargeFileData(): Promise<CleanupResult> {
    const startTime = performance.now()
    let freedMemory = 0
    let itemsRemoved = 0
    
    try {
      const beforeUsage = this.fileDataStore.getMemoryUsage()
      
      // 清理所有文件数据（紧急情况下）
      this.fileDataStore.clearAllFileData()
      
      freedMemory = beforeUsage.totalSize / (1024 * 1024) // 转换为MB
      itemsRemoved = beforeUsage.fileCount
      
      console.warn(`[MemoryManagement] 紧急清理文件数据完成，释放: ${freedMemory.toFixed(2)}MB`)
    } catch (error) {
      console.error('[MemoryManagement] 清理文件数据失败:', error)
    }
    
    const duration = performance.now() - startTime
    
    return {
      freedMemory,
      itemsRemoved,
      strategy: CleanupStrategy.SIZE_BASED,
      duration,
      success: true
    }
  }

  /**
   * 强制垃圾回收
   */
  private forceGarbageCollection(): void {
    try {
      // 在支持的环境中触发垃圾回收
      if ('gc' in window && typeof (window as any).gc === 'function') {
        (window as any).gc()
        console.log('[MemoryManagement] 触发垃圾回收')
      }
    } catch (error) {
      // 忽略错误，垃圾回收不是必需的
    }
  }

  /**
   * 估算可用内存
   */
  private estimateAvailableMemory(): number {
    try {
      // 基于浏览器的内存限制估算
      // 现代浏览器通常允许每个标签页使用1-4GB内存
      const estimatedLimit = 2048 // 2GB
      const currentUsage = this.getCurrentMemoryUsage()
      return Math.max(0, estimatedLimit - currentUsage)
    } catch (error) {
      return 1024 // 默认1GB可用
    }
  }

  /**
   * 获取当前内存使用量
   */
  private getCurrentMemoryUsage(): number {
    try {
      // 使用performance.memory API（如果可用）
      if ('memory' in performance) {
        const memory = (performance as any).memory
        return memory.usedJSHeapSize / (1024 * 1024) // 转换为MB
      }
    } catch (error) {
      // API不可用时的fallback
    }
    return 0
  }

  /**
   * 添加到历史记录
   */
  private addToHistory(stats: MemoryStats): void {
    this.memoryHistory.push(stats)
    
    // 保持历史记录大小限制
    if (this.memoryHistory.length > this.maxHistorySize) {
      this.memoryHistory.shift()
    }
  }

  /**
   * 创建空的清理结果
   */
  private createEmptyCleanupResult(): CleanupResult {
    return {
      freedMemory: 0,
      itemsRemoved: 0,
      strategy: CleanupStrategy.LRU,
      duration: 0,
      success: false
    }
  }

  /**
   * 获取内存历史记录
   */
  getMemoryHistory(): MemoryStats[] {
    return [...this.memoryHistory]
  }

  /**
   * 获取内存趋势
   */
  getMemoryTrend(minutes: number = 10): {
    trend: 'increasing' | 'decreasing' | 'stable'
    averageUsage: number
    peakUsage: number
  } {
    const cutoffTime = Date.now() - (minutes * 60 * 1000)
    const recentStats = this.memoryHistory.filter(stat => stat.timestamp > cutoffTime)
    
    if (recentStats.length < 2) {
      return {
        trend: 'stable',
        averageUsage: 0,
        peakUsage: 0
      }
    }
    
    const totalUsages = recentStats.map(stat => stat.totalUsed)
    const averageUsage = totalUsages.reduce((sum, usage) => sum + usage, 0) / totalUsages.length
    const peakUsage = Math.max(...totalUsages)
    
    // 计算趋势
    const firstHalf = totalUsages.slice(0, Math.floor(totalUsages.length / 2))
    const secondHalf = totalUsages.slice(Math.floor(totalUsages.length / 2))
    
    const firstAvg = firstHalf.reduce((sum, usage) => sum + usage, 0) / firstHalf.length
    const secondAvg = secondHalf.reduce((sum, usage) => sum + usage, 0) / secondHalf.length
    
    const threshold = averageUsage * 0.1 // 10%的变化阈值
    
    let trend: 'increasing' | 'decreasing' | 'stable'
    if (secondAvg - firstAvg > threshold) {
      trend = 'increasing'
    } else if (firstAvg - secondAvg > threshold) {
      trend = 'decreasing'
    } else {
      trend = 'stable'
    }
    
    return {
      trend,
      averageUsage,
      peakUsage
    }
  }

  /**
   * 设置内存阈值
   */
  setThresholds(thresholds: Partial<MemoryThresholds>): void {
    this.thresholds = { ...this.thresholds, ...thresholds }
    console.log('[MemoryManagement] 更新内存阈值:', this.thresholds)
  }

  /**
   * 获取当前阈值
   */
  getThresholds(): MemoryThresholds {
    return { ...this.thresholds }
  }

  /**
   * 销毁服务
   */
  destroy(): void {
    this.stopMonitoring()
    this.memoryHistory = []
    console.log('[MemoryManagement] 内存管理服务已销毁')
  }
}

// 全局内存管理服务实例
export const memoryManagementService = new MemoryManagementService()